package com.zzyl.controller;

import cn.hutool.core.bean.BeanUtil;
import com.zzyl.base.PageResponse;
import com.zzyl.base.ResponseResult;
import com.zzyl.dto.RoleDto;
import com.zzyl.entity.Role;
import com.zzyl.service.RoleService;
import com.zzyl.vo.RoleVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    /**
     * 角色分页查询
     * @param pageNum
     * @param pageSize
     * @param dto
     * @return
     */
    @PostMapping("/page/{pageNum}/{pageSize}")
    public ResponseResult<PageResponse<RoleVo>> findByPage(
            @PathVariable(name = "pageNum") Integer pageNum,
            @PathVariable(name = "pageSize") Integer pageSize,
            @RequestBody RoleDto dto
            ){
        PageResponse<RoleVo> page = roleService.findByPage(pageNum,pageSize,dto.getRoleName());
        return ResponseResult.success(page);
    }

    /**
     * 添加角色
     * @param dto
     * @return
     */
    @PutMapping
    public ResponseResult saveRole(@RequestBody RoleDto dto){
//        对象属性拷贝
        Role role = BeanUtil.toBean(dto, Role.class);
        roleService.saveRole(role);
        return ResponseResult.success();
    }

    /**
     * 根据roleid 查询选中的资源数据
     * @param roleId
     * @return
     */
    @GetMapping("/find-checked-resources/{roleId}")
    public ResponseResult<Set<String>> findCheckedResources(@PathVariable(name = "roleId") Long roleId){
        Set<String> resources = roleService.findCheckedResources(roleId);
        return ResponseResult.success(resources);
    }

    /**
     * 修改角色资源关系表
     * @param dto
     * @return
     */
    @PatchMapping
    public ResponseResult updateRole(@RequestBody RoleDto dto){
        roleService.updateRole(dto);
        return ResponseResult.success();
    }

    /**
     * 根据角色id 删除角色信息和角色资源中间表
     * @param roleId
     * @return
     */
    @DeleteMapping("/{roleIds}")
    public ResponseResult deleteRole(@PathVariable(name = "roleIds") Long roleId){
        roleService.deleteRole(roleId);
        return ResponseResult.success();
    }

    @PostMapping("init-roles")
    @ApiOperation(value = "角色下拉框",notes = "角色下拉框")
    ResponseResult<List<RoleVo>> initRoles() {
        List<RoleVo> roleVoResult = roleService.initRoles();
        return ResponseResult.success(roleVoResult);
    }
}
